package utils;

import com.github.houbb.opencc4j.util.ZhConverterUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author Zhang Guangyong
 * @desacription
 * @date 2019年07月23日 9:55
 */
public class HtmlUtils {

    /**
     * xml文件简繁转换
     *
     * @param xmlPath : xml文件路径
     * @param outPath : 文件输出路径
     * @param flag    : 1/2 简繁标识
     * @author 张广勇
     * @date 2019/7/23 9:14
     */
    public static void changeSimpleOrTraditional(String xmlPath, String outPath, String flag) {
        File file = new File(xmlPath);
        Document document;
        String docStrAft;
        try {
            document = Jsoup.parse(file, "UTF-8", "");
            if (document != null) {
                String docStr = document.toString();
                if ("1".equals(flag)) {
                    docStrAft = ZhConverterUtil.convertToSimple(docStr);
                } else if ("2".equals(flag)) {
                    docStrAft = ZhConverterUtil.convertToTraditional(docStr);
                } else {
                    System.out.println("标识符不规范 不作处理");
                    return;
                }
                String replace = docStrAft.replace("<!--?xml version=\"1.0\" encoding=\"utf-8\"?-->",
                        "");
                Document docAft = Jsoup.parse(replace);
                File oldFile = new File(outPath);
                oldFile.createNewFile();
                FileWriter fileWriter = new FileWriter(file);
                fileWriter.write("");
                fileWriter.flush();
                fileWriter.close();
                FileOutputStream fos = new FileOutputStream(outPath, true);
                // 覆盖写入原文件
                fos.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>".getBytes());
                fos.write(docAft.html().getBytes());
                fos.close();
            } else {
                System.out.println("解析xhtml为空");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
